from index import index
from flask import Flask, request, render_template, redirect, url_for, session, flash
from models import User, Blog, Column, Youlian
from exts import db


@index.route('/m/')
@index.route('/')
def index_index():
    data = {'title': '网站首页'}
    data['column'] = Column.query.all()
    data['user'] = User.query.first()
    page = request.args.get('page', 1, type=int)
    pagination = Blog.query.order_by(Blog.id.desc()).join(User, Blog.uid == User.id).add_entity(User).paginate(page,
                                                                                                               per_page=5,
                                                                                                               error_out=False)
    data['blog'] = pagination.items
    data['blog_hot'] = Blog.query.order_by(Blog.read.desc()).limit(8).all()
    data['youlian'] = Youlian.query.all()
    if request.path.startswith('/m/'):
        tpl = './index/m_index.html'
    else:
        tpl = './index/index.html'
    return render_template(tpl, data=data, pagination=pagination)


@index.route('/article/<int:id>')
def index_article(id):
    data = {}
    data['column'] = Column.query.all()
    data['blog'] = Blog.query.filter(Blog.id == id).order_by(Blog.id.desc()).join(Column,
                                                                                  Blog.fid == Column.id).add_entity(
        Column).first()
    data['blog_hot'] = Blog.query.order_by(Blog.read.desc()).limit(8).all()
    blog = Blog.query.filter(Blog.id == id).first()
    blog.read = blog.read + 1
    db.session.add(blog)
    db.session.commit()
    blog = data['blog'][0]
    data['blog_prev'] = Blog.query.filter(Blog.id > id, Blog.fid == blog.fid).first()
    data['blog_next'] = Blog.query.filter(Blog.id < id, Blog.fid == blog.fid).first()
    return render_template('./index/article.html', data=data)


@index.route('/list/<int:id>/')
def index_list(id):
    data = {}
    data['column'] = Column.query.all()
    page = request.args.get('page', 1, type=int)
    pagination = Blog.query.filter(Blog.fid == id).order_by(Blog.id.desc()).join(User, Blog.uid == User.id).add_entity(
        User).paginate(page, per_page=5, error_out=False)
    data['blog'] = pagination.items
    data['column_new'] = Column.query.filter(Column.id == id).first()
    return render_template('./index/list.html', data=data, pagination=pagination, id=str(id))